﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;

namespace MedievalGameProject
{
    public class ThirdPersonCamera : GameComponent
    {
        public Matrix view { get; protected set; }
        public Matrix projection { get; protected set; }

        public Vector3 cameraPosition { get; set; }
        public Vector3 cameraDirection;
        public Vector3 cameraUp;
        public Vector3 actualCameraUp;

        public BoundingFrustum frustum { get; protected set; }

        MouseState prevMouseState;
        float rightShoulderOffset = 5;
        float minCameraDist = 5;
        float currCameraZoom = 20;
        float maxCameraDist = 50;

        public Actor target;


        public ThirdPersonCamera(Game game, Vector3 pos, Actor target, Vector3 up)
            : base(game)
        {
            this.target = target;

            projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4,
                (float)game.Window.ClientBounds.Width / (float)game.Window.ClientBounds.Height, 1, 30000);
            cameraPosition = pos;

            if (target == null)
                cameraDirection = Vector3.UnitZ;
            else
                cameraDirection = target.position - pos;

            cameraDirection.Normalize(); //Make it a unit vector
            
            cameraUp = up;
            actualCameraUp = up;

            Mouse.SetPosition(Game.Window.ClientBounds.Width / 2, Game.Window.ClientBounds.Height / 2);
            prevMouseState = Mouse.GetState();


            CreateLookAt();

        }

        public override void Initialize()
        {
            base.Initialize();

            if(target != null)
                target.SetFacingDirection2D(cameraDirection);
        }

        private void CreateLookAt()
        {
            view = Matrix.CreateLookAt(cameraPosition, cameraPosition + cameraDirection, cameraUp);
        }

        public override void Update(GameTime gameTime)
        {
            if (Game1.currentGameState == GameState.InGame)
            {
                base.Update(gameTime);

                frustum = new BoundingFrustum(view * projection);

                MouseState state = Mouse.GetState();

                CheckZoom();

                FollowTarget(gameTime);

                CheckRotations();

                CreateLookAt();

                if (Game.IsActive)
                {
                    Mouse.SetPosition(Game.Window.ClientBounds.Width / 2, Game.Window.ClientBounds.Height / 2);
                    prevMouseState = Mouse.GetState();
                }
            }
        }

        private void CheckZoom()
        {
            MouseState state = Mouse.GetState();

            int scrollValueDiff = prevMouseState.ScrollWheelValue - state.ScrollWheelValue;

            if (scrollValueDiff > 0) 
            {
                if (currCameraZoom + 1 <= maxCameraDist)
                    currCameraZoom++;
            } 
            else if ( scrollValueDiff < 0) 
            {
                if (currCameraZoom - 1 >= minCameraDist)
                    currCameraZoom--;
            }
                
        }

        private void CheckRotations()
        {
            MouseState state = Mouse.GetState();

            if (state.X - prevMouseState.X != 0 || state.Y - prevMouseState.Y != 0)
            {

                Vector3 distToLerp = Vector3.Cross(cameraUp, cameraDirection) * (MathHelper.PiOver4)
                    * (state.X - prevMouseState.X);

                LerpDistance(distToLerp, 20);

                actualCameraUp = Vector3.Cross(Vector3.Cross(cameraUp, cameraDirection), cameraDirection);

                distToLerp = actualCameraUp * (-MathHelper.PiOver4) * (state.Y - prevMouseState.Y);

                LerpDistance(distToLerp, 20);

                if (target != null)
                    target.SetFacingDirection2D(cameraDirection);
            }
        }

        private void LerpDistance(Vector3 distance, int timesToLerp)
        {
            Vector3 distToMoveEachTime = distance / timesToLerp;

            for (int i = 0; i < timesToLerp; i++)
            {
                cameraPosition += distToMoveEachTime;
                LookAtTarget();
            }
        }

        private void FollowTarget(GameTime gameTime)
        {
            cameraPosition = target.position + CalculateOTSOffset() - cameraDirection * currCameraZoom;

            LookAtTarget();
        }

        //Makes camera look directly at the target, useful after moving the camera
        private void LookAtTarget()
        {
            cameraDirection = target.position + CalculateOTSOffset() - cameraPosition;
            cameraDirection.Normalize();
        }

        private Vector3 CalculateOTSOffset()
        {
            Vector3 strafe = Vector3.Cross(cameraUp, cameraDirection);
            strafe.Normalize();
            Vector3 overShoulderOffset = strafe * -rightShoulderOffset;

            return overShoulderOffset;
        }

        public Vector3 GetStrafeDirection()
        {
            return Vector3.Cross(cameraUp, cameraDirection);
        }

        public void SetTarget(Actor target)
        {
            this.target = target;
            cameraDirection = target.direction;
            cameraPosition = target.position - (cameraDirection * maxCameraDist);
        }
    }

}
